local skel = fk.CreateSkill {
  name = "emo__mingdie",
  tags = {Skill.Compulsory},
}

skel:addEffect(fk.GameStart, {
  anim_type = "drawcard",
  derived_piles = "emo__DeadButterfly&",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(skel.name)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local suits, ids = {}, {}
    for _, id in ipairs(room.draw_pile) do
      if Fk:getCardById(id).suit ~= Card.NoSuit then
        if table.insertIfNeed(suits, Fk:getCardById(id).suit) then
          table.insert(ids, id)
          if #ids == 4 then break end
        end
      end
    end
    if #ids == 0 then return end
    player:addToPile("emo__DeadButterfly&", ids, true, skel.name)
  end,
})

local can_trigger = function(self, event, target, player, data)
  if player:hasSkill(skel.name) then
    return target == player and (data.extra_data or {}).emo__mingdieCheck and data.card.suit ~= Card.NoSuit
  end
end

local on_use = function (self, event, target, player, data)
  local room = player.room
  room:delay(600)
  room:doIndicate(player, room.alive_players)
  for _, p in ipairs(room:getAlivePlayers()) do
    if not p.dead then
      local cards = table.filter(p:getCardIds("h"), function (id)
        return Fk:getCardById(id).suit == data.card.suit
      end)
      if #cards > 0 then
        room:throwCard(table.random(cards), skel.name, p, p)
      else
        room:loseHp(p, 1, skel.name)
      end
    end
  end
end

skel:addEffect(fk.CardUseFinished, {
  anim_type = "offensive",
  can_trigger = can_trigger,
  on_use = on_use,
})

skel:addEffect(fk.CardRespondFinished, {
  anim_type = "offensive",
  can_trigger = can_trigger,
  on_use = on_use,
})

local can_refresh = function (self, event, target, player, data)
  return target == player and table.contains(player:getPile("emo__DeadButterfly&"), data.card:getEffectiveId())
end
local on_refresh = function (self, event, target, player, data)
  if event == fk.PreCardUse then
    data.extraUse = true
  end
  data.extra_data = data.extra_data or {}
  data.extra_data.emo__mingdieCheck = true
end

skel:addEffect(fk.PreCardUse, {
  can_refresh = can_refresh,
  on_refresh = on_refresh,
})

skel:addEffect(fk.PreCardRespond, {
  can_refresh = can_refresh,
  on_refresh = on_refresh,
})

skel:addEffect("targetmod", {
  bypass_times = function(self, player, skill, scope, card, to)
    return card and table.contains(player:getPile("emo__DeadButterfly&"), card:getEffectiveId())
  end,
  bypass_distances = function(self, player, skill, card, to)
    return card and table.contains(player:getPile("emo__DeadButterfly&"), card:getEffectiveId())
  end,
})


Fk:loadTranslationTable{
  ["emo__mingdie"] = "冥蝶",
  [":emo__mingdie"] = "锁定技，游戏开始时，你将牌堆每花色各一张牌置于武将牌上称为“蝶”，“蝶”可无距离次数限制地如手牌使用或打出，且结算后令所有角色各随机弃置一张与此“蝶”花色相同的手牌，若未弃牌则其失去1点体力。",
  ["emo__DeadButterfly&"] = "蝶",
}


return skel
